using UnityEngine;
using TMPro;
using System.Collections;

/// <summary>
/// 角色UI管理器
/// 负责角色相关的UI显示和动画效果
/// </summary>
public class CharacterUIManager : MonoBehaviour
{
    [Header("伤害数字")]
    [SerializeField] private GameObject damageNumberPrefab;
    [SerializeField] private Transform damageNumberParent;
    [SerializeField] private float damageNumberDuration = 2.0f;
    [SerializeField] private float damageNumberFloatHeight = 100f;
    
    [Header("治疗数字")]
    [SerializeField] private GameObject healNumberPrefab;
    [SerializeField] private Color damageColor = Color.red;
    [SerializeField] private Color healColor = Color.green;
    [SerializeField] private Color criticalDamageColor = Color.yellow;
    
    [Header("角色动画")]
    [SerializeField] private float attackAnimationDuration = 0.5f;
    [SerializeField] private float hurtAnimationDuration = 0.3f;
    [SerializeField] private float healAnimationDuration = 0.5f;
    
    [Header("技能特效")]
    [SerializeField] private GameObject[] skillEffectPrefabs;
    
    // 角色UI字典
    private System.Collections.Generic.Dictionary<string, CharacterUI> characterUIs = new System.Collections.Generic.Dictionary<string, CharacterUI>();
    
    private void Start()
    {
        InitializeCharacterUIs();
    }
    
    /// <summary>
    /// 初始化角色UI
    /// </summary>
    private void InitializeCharacterUIs()
    {
        // 查找所有角色UI组件
        CharacterUI[] allCharacterUIs = FindObjectsOfType<CharacterUI>();
        
        foreach (var characterUI in allCharacterUIs)
        {
            if (!string.IsNullOrEmpty(characterUI.CharacterId))
            {
                characterUIs[characterUI.CharacterId] = characterUI;
            }
        }
        
        Debug.Log($"初始化了 {characterUIs.Count} 个角色UI");
    }
    
    /// <summary>
    /// 更新角色信息
    /// </summary>
    public void UpdateCharacters(BattleStateData battleState)
    {
        // 更新队伍1的角色
        if (battleState.teams != null && battleState.teams.Length > 0)
        {
            UpdateTeamCharacters(battleState.teams[0]);
        }
        
        // 更新队伍2的角色
        if (battleState.teams != null && battleState.teams.Length > 1)
        {
            UpdateTeamCharacters(battleState.teams[1]);
        }
    }
    
    /// <summary>
    /// 更新队伍角色
    /// </summary>
    private void UpdateTeamCharacters(TeamData team)
    {
        if (team.characters == null) return;
        
        foreach (var character in team.characters)
        {
            if (characterUIs.ContainsKey(character.id))
            {
                characterUIs[character.id].UpdateCharacterData(character);
            }
        }
    }
    
    /// <summary>
    /// 显示伤害数字
    /// </summary>
    public void ShowDamage(string characterId, int damage, bool isCritical = false)
    {
        if (!characterUIs.ContainsKey(characterId))
        {
            Debug.LogWarning($"未找到角色UI: {characterId}");
            return;
        }
        
        CharacterUI characterUI = characterUIs[characterId];
        StartCoroutine(ShowDamageNumberCoroutine(characterUI, damage, isCritical));
        
        // 播放受伤动画
        StartCoroutine(PlayHurtAnimationCoroutine(characterUI));
    }
    
    /// <summary>
    /// 显示治疗数字
    /// </summary>
    public void ShowHeal(string characterId, int heal)
    {
        if (!characterUIs.ContainsKey(characterId))
        {
            Debug.LogWarning($"未找到角色UI: {characterId}");
            return;
        }
        
        CharacterUI characterUI = characterUIs[characterId];
        StartCoroutine(ShowHealNumberCoroutine(characterUI, heal));
        
        // 播放治疗动画
        StartCoroutine(PlayHealAnimationCoroutine(characterUI));
    }
    
    /// <summary>
    /// 更新角色HP
    /// </summary>
    public void UpdateCharacterHP(string characterId, int currentHp)
    {
        if (!characterUIs.ContainsKey(characterId))
        {
            Debug.LogWarning($"未找到角色UI: {characterId}");
            return;
        }
        
        characterUIs[characterId].UpdateHP(currentHp);
    }
    
    /// <summary>
    /// 更新角色MP
    /// </summary>
    public void UpdateCharacterMP(string characterId, int currentMp)
    {
        if (!characterUIs.ContainsKey(characterId))
        {
            Debug.LogWarning($"未找到角色UI: {characterId}");
            return;
        }
        
        characterUIs[characterId].UpdateMP(currentMp);
    }
    
    /// <summary>
    /// 显示状态效果
    /// </summary>
    public void ShowStatusEffect(string characterId, string effectName, bool applied)
    {
        if (!characterUIs.ContainsKey(characterId))
        {
            Debug.LogWarning($"未找到角色UI: {characterId}");
            return;
        }
        
        characterUIs[characterId].ShowStatusEffect(effectName, applied);
    }
    
    /// <summary>
    /// 播放攻击动画
    /// </summary>
    public void PlayAttackAnimation(string characterId)
    {
        if (!characterUIs.ContainsKey(characterId))
        {
            Debug.LogWarning($"未找到角色UI: {characterId}");
            return;
        }
        
        StartCoroutine(PlayAttackAnimationCoroutine(characterUIs[characterId]));
    }
    
    /// <summary>
    /// 显示技能特效
    /// </summary>
    public void ShowSkillEffect(string characterId, string skillId, string targetId)
    {
        if (!characterUIs.ContainsKey(characterId))
        {
            Debug.LogWarning($"未找到角色UI: {characterId}");
            return;
        }
        
        if (!characterUIs.ContainsKey(targetId))
        {
            Debug.LogWarning($"未找到目标角色UI: {targetId}");
            return;
        }
        
        CharacterUI casterUI = characterUIs[characterId];
        CharacterUI targetUI = characterUIs[targetId];
        
        StartCoroutine(ShowSkillEffectCoroutine(casterUI, targetUI, skillId));
    }
    
    /// <summary>
    /// 显示伤害数字协程
    /// </summary>
    private IEnumerator ShowDamageNumberCoroutine(CharacterUI characterUI, int damage, bool isCritical)
    {
        // 创建伤害数字
        GameObject damageNumberObj = Instantiate(damageNumberPrefab, damageNumberParent);
        TextMeshProUGUI damageText = damageNumberObj.GetComponent<TextMeshProUGUI>();
        
        if (damageText)
        {
            damageText.text = damage.ToString();
            damageText.color = isCritical ? criticalDamageColor : damageColor;
            damageText.fontSize = isCritical ? damageText.fontSize * 1.5f : damageText.fontSize;
        }
        
        // 设置初始位置
        Vector3 startPos = characterUI.GetDamageNumberPosition();
        damageNumberObj.transform.position = startPos;
        
        // 动画效果
        float timer = 0;
        Vector3 endPos = startPos + Vector3.up * damageNumberFloatHeight;
        
        while (timer < damageNumberDuration)
        {
            timer += Time.deltaTime;
            float progress = timer / damageNumberDuration;
            
            // 位置插值
            damageNumberObj.transform.position = Vector3.Lerp(startPos, endPos, progress);
            
            // 透明度渐变
            if (damageText)
            {
                Color color = damageText.color;
                color.a = 1.0f - progress;
                damageText.color = color;
            }
            
            yield return null;
        }
        
        Destroy(damageNumberObj);
    }
    
    /// <summary>
    /// 显示治疗数字协程
    /// </summary>
    private IEnumerator ShowHealNumberCoroutine(CharacterUI characterUI, int heal)
    {
        // 创建治疗数字
        GameObject healNumberObj = Instantiate(healNumberPrefab, damageNumberParent);
        TextMeshProUGUI healText = healNumberObj.GetComponent<TextMeshProUGUI>();
        
        if (healText)
        {
            healText.text = $"+{heal}";
            healText.color = healColor;
        }
        
        // 设置初始位置
        Vector3 startPos = characterUI.GetDamageNumberPosition();
        healNumberObj.transform.position = startPos;
        
        // 动画效果
        float timer = 0;
        Vector3 endPos = startPos + Vector3.up * damageNumberFloatHeight;
        
        while (timer < damageNumberDuration)
        {
            timer += Time.deltaTime;
            float progress = timer / damageNumberDuration;
            
            // 位置插值
            healNumberObj.transform.position = Vector3.Lerp(startPos, endPos, progress);
            
            // 透明度渐变
            if (healText)
            {
                Color color = healText.color;
                color.a = 1.0f - progress;
                healText.color = color;
            }
            
            yield return null;
        }
        
        Destroy(healNumberObj);
    }
    
    /// <summary>
    /// 播放攻击动画协程
    /// </summary>
    private IEnumerator PlayAttackAnimationCoroutine(CharacterUI characterUI)
    {
        Vector3 originalPosition = characterUI.transform.position;
        Vector3 targetPosition = originalPosition + characterUI.transform.forward * 0.5f;
        
        // 前进
        float timer = 0;
        while (timer < attackAnimationDuration * 0.5f)
        {
            timer += Time.deltaTime;
            float progress = timer / (attackAnimationDuration * 0.5f);
            characterUI.transform.position = Vector3.Lerp(originalPosition, targetPosition, progress);
            yield return null;
        }
        
        // 返回
        timer = 0;
        while (timer < attackAnimationDuration * 0.5f)
        {
            timer += Time.deltaTime;
            float progress = timer / (attackAnimationDuration * 0.5f);
            characterUI.transform.position = Vector3.Lerp(targetPosition, originalPosition, progress);
            yield return null;
        }
        
        characterUI.transform.position = originalPosition;
    }
    
    /// <summary>
    /// 播放受伤动画协程
    /// </summary>
    private IEnumerator PlayHurtAnimationCoroutine(CharacterUI characterUI)
    {
        Color originalColor = characterUI.GetCharacterColor();
        Color hurtColor = Color.red;
        
        // 闪烁效果
        float timer = 0;
        bool isRed = false;
        
        while (timer < hurtAnimationDuration)
        {
            timer += Time.deltaTime;
            isRed = !isRed;
            characterUI.SetCharacterColor(isRed ? hurtColor : originalColor);
            yield return new WaitForSeconds(0.1f);
        }
        
        characterUI.SetCharacterColor(originalColor);
    }
    
    /// <summary>
    /// 播放治疗动画协程
    /// </summary>
    private IEnumerator PlayHealAnimationCoroutine(CharacterUI characterUI)
    {
        Color originalColor = characterUI.GetCharacterColor();
        Color healColor = Color.green;
        
        // 渐变效果
        float timer = 0;
        while (timer < healAnimationDuration)
        {
            timer += Time.deltaTime;
            float progress = timer / healAnimationDuration;
            Color currentColor = Color.Lerp(healColor, originalColor, progress);
            characterUI.SetCharacterColor(currentColor);
            yield return null;
        }
        
        characterUI.SetCharacterColor(originalColor);
    }
    
    /// <summary>
    /// 显示技能特效协程
    /// </summary>
    private IEnumerator ShowSkillEffectCoroutine(CharacterUI casterUI, CharacterUI targetUI, string skillId)
    {
        // 根据技能ID选择特效
        GameObject effectPrefab = GetSkillEffectPrefab(skillId);
        if (effectPrefab == null)
        {
            Debug.LogWarning($"未找到技能特效: {skillId}");
            yield break;
        }
        
        // 在施法者位置创建特效
        GameObject effectObj = Instantiate(effectPrefab, casterUI.transform.position, Quaternion.identity);
        
        // 移动到目标位置
        float timer = 0;
        Vector3 startPos = casterUI.transform.position;
        Vector3 endPos = targetUI.transform.position;
        
        while (timer < 1.0f)
        {
            timer += Time.deltaTime;
            float progress = timer / 1.0f;
            effectObj.transform.position = Vector3.Lerp(startPos, endPos, progress);
            yield return null;
        }
        
        // 播放目标位置特效
        if (targetUI != null)
        {
            // 可以在这里添加目标位置的爆炸效果等
        }
        
        Destroy(effectObj);
    }
    
    /// <summary>
    /// 根据技能ID获取特效预制体
    /// </summary>
    private GameObject GetSkillEffectPrefab(string skillId)
    {
        // 这里可以根据技能ID返回对应的特效预制体
        // 暂时返回第一个特效作为示例
        if (skillEffectPrefabs != null && skillEffectPrefabs.Length > 0)
        {
            return skillEffectPrefabs[0];
        }
        return null;
    }
}

/// <summary>
/// 角色UI组件
/// </summary>
public class CharacterUI : MonoBehaviour
{
    [Header("角色信息")]
    [SerializeField] private string characterId;
    [SerializeField] private TextMeshProUGUI nameText;
    [SerializeField] private Slider hpSlider;
    [SerializeField] private Slider mpSlider;
    [SerializeField] private TextMeshProUGUI hpText;
    [SerializeField] private TextMeshProUGUI mpText;
    [SerializeField] private SpriteRenderer characterRenderer;
    
    [Header("状态效果")]
    [SerializeField] private Transform statusEffectsPanel;
    [SerializeField] private GameObject statusEffectPrefab;
    
    private System.Collections.Generic.Dictionary<string, GameObject> statusEffectObjects = new System.Collections.Generic.Dictionary<string, GameObject>();
    
    public string CharacterId => characterId;
    
    /// <summary>
    /// 更新角色数据
    /// </summary>
    public void UpdateCharacterData(CharacterData character)
    {
        // 更新基本信息
        if (nameText) nameText.text = character.name;
        
        // 更新HP
        UpdateHP(character.hp);
        
        // 更新MP
        UpdateMP(character.mp);
        
        // 更新状态效果
        UpdateStatusEffects(character.statusEffects);
    }
    
    /// <summary>
    /// 更新HP
    /// </summary>
    public void UpdateHP(int currentHp)
    {
        if (hpSlider)
        {
            hpSlider.value = currentHp;
        }
        
        if (hpText)
        {
            int maxHp = (int)hpSlider.maxValue;
            hpText.text = $"{currentHp}/{maxHp}";
        }
    }
    
    /// <summary>
    /// 更新MP
    /// </summary>
    public void UpdateMP(int currentMp)
    {
        if (mpSlider)
        {
            mpSlider.value = currentMp;
        }
        
        if (mpText)
        {
            int maxMp = (int)mpSlider.maxValue;
            mpText.text = $"{currentMp}/{maxMp}";
        }
    }
    
    /// <summary>
    /// 更新状态效果
    /// </summary>
    private void UpdateStatusEffects(StatusEffectData[] statusEffects)
    {
        if (!statusEffectsPanel) return;
        
        // 清除现有状态效果
        foreach (var kvp in statusEffectObjects)
        {
            Destroy(kvp.Value);
        }
        statusEffectObjects.Clear();
        
        // 添加新状态效果
        foreach (var effect in statusEffects)
        {
            GameObject effectObj = Instantiate(statusEffectPrefab, statusEffectsPanel);
            StatusEffectUI effectUI = effectObj.GetComponent<StatusEffectUI>();
            
            if (effectUI)
            {
                effectUI.UpdateStatusEffect(effect);
            }
            
            statusEffectObjects[effect.name] = effectObj;
        }
    }
    
    /// <summary>
    /// 显示状态效果
    /// </summary>
    public void ShowStatusEffect(string effectName, bool applied)
    {
        if (applied)
        {
            // 状态效果施加动画
            if (statusEffectObjects.ContainsKey(effectName))
            {
                GameObject effectObj = statusEffectObjects[effectName];
                StartCoroutine(PlayStatusEffectApplyAnimation(effectObj));
            }
        }
        else
        {
            // 状态效果移除动画
            if (statusEffectObjects.ContainsKey(effectName))
            {
                GameObject effectObj = statusEffectObjects[effectName];
                StartCoroutine(PlayStatusEffectRemoveAnimation(effectObj, () => {
                    statusEffectObjects.Remove(effectName);
                }));
            }
        }
    }
    
    /// <summary>
    /// 获取伤害数字显示位置
    /// </summary>
    public Vector3 GetDamageNumberPosition()
    {
        return transform.position + Vector3.up * 2f;
    }
    
    /// <summary>
    /// 获取角色颜色
    /// </summary>
    public Color GetCharacterColor()
    {
        if (characterRenderer)
        {
            return characterRenderer.color;
        }
        return Color.white;
    }
    
    /// <summary>
    /// 设置角色颜色
    /// </summary>
    public void SetCharacterColor(Color color)
    {
        if (characterRenderer)
        {
            characterRenderer.color = color;
        }
    }
    
    /// <summary>
    /// 播放状态效果施加动画
    /// </summary>
    private IEnumerator PlayStatusEffectApplyAnimation(GameObject effectObj)
    {
        Vector3 originalScale = effectObj.transform.localScale;
        effectObj.transform.localScale = Vector3.zero;
        
        float timer = 0;
        while (timer < 0.3f)
        {
            timer += Time.deltaTime;
            float progress = timer / 0.3f;
            effectObj.transform.localScale = Vector3.Lerp(Vector3.zero, originalScale, progress);
            yield return null;
        }
        
        effectObj.transform.localScale = originalScale;
    }
    
    /// <summary>
    /// 播放状态效果移除动画
    /// </summary>
    private IEnumerator PlayStatusEffectRemoveAnimation(GameObject effectObj, System.Action onComplete)
    {
        Vector3 originalScale = effectObj.transform.localScale;
        
        float timer = 0;
        while (timer < 0.3f)
        {
            timer += Time.deltaTime;
            float progress = timer / 0.3f;
            effectObj.transform.localScale = Vector3.Lerp(originalScale, Vector3.zero, progress);
            yield return null;
        }
        
        Destroy(effectObj);
        onComplete?.Invoke();
    }
}